import store from "@/store/index.js"
const path = {
	state: {
		list:[
			{
				name:"张三",
				tel:"13782794601",
				city:"成都市成华区猛追湾街",
				details:"3号",
				isDefault:false
			},
			{
				name:"李四",
				tel:"13782794601",
				city:"成都市金牛区光荣北路",
				details:"3栋2号",
				isDefault:true
			}
		]
	},
	mutations: {
		//读取收货地址
		initPath(state){
			let openId = store.state.user.userInfo.openId || store.state.user.userInfo.phone
			let pathInfo = undefined
			if(openId){
				pathInfo = uni.getStorageSync(openId)
			}else if(pathInfo){
				state.list = JSON.parse(pathInfo)
			}
		},
		addPath(state,value){
			isDefaultFn(state,value)
			state.list.push(value)
			//持久化保存数据
			let openId = store.state.user.userInfo.openId || store.state.user.userInfo.phone
			uni.setStorageSync(openId,JSON.stringify(state.list))
		},
		updatePath(state,{index,item}){
			isDefaultFn(state,item)
			state.list[index] = item
			//持久化保存数据
			let openId = store.state.user.userInfo.openId || store.state.user.userInfo.phone
			uni.setStorageSync(openId,JSON.stringify(state.list))
		},
		//切换默认地址
		defaultPath(state,item){
			let index = state.list.indexOf(item)
			state.list.forEach(v=>{
				v.isDefault = false
			})
			state.list[index].isDefault = true
			//持久化保存数据
			let openId = store.state.user.userInfo.openId || store.state.user.userInfo.phone
			uni.setStorageSync(openId,JSON.stringify(state.list))
		},
		//删除地址
		deletePath(state,index){
			state.list.splice(index,1)
			//持久化保存数据
			let openId = store.state.user.userInfo.openId || store.state.user.userInfo.phone
			uni.setStorageSync(openId,JSON.stringify(state.list))
		}
	},
	actions: {
	
	},
	getters: {
		isDefaultPath(state){
			return state.list.filter(v=>v.isDefault)
		}
	}
}
//设置默认
const isDefaultFn = (state,item)=>{
	if(item.isDefault){//是否设置为默认地址
		state.list.forEach(v=>{
			v.isDefault = false
		})
		item.isDefault = true
	}
}
export default path
